package com.zzyk.main.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.zzyk.main.configuration.exception.DeviceException;
import com.zzyk.main.mapper.*;
import com.zzyk.main.model.pojo.*;
import com.zzyk.main.model.vo.*;
import com.zzyk.main.service.DeviceService;
import com.zzyk.main.service.GroupDeviceService;
import com.zzyk.main.utils.CalculateUtils;
import com.zzyk.main.utils.FTPUtils;
import com.zzyk.main.utils.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * @author wss_PC
 */
@Service
public class DeviceServiceImpl implements DeviceService {
    @Value("${ftp.deviceDir}")
    private String deviceDir;
    private Date toDay = DateUtil.date();
    @Resource
    private DeviceMapper deviceMapper;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private DeviceOriginDataMapper deviceOriginDataMapper;
    @Autowired
    private DeviceExtraDataMapper deviceExtraDataMapper;
    @Autowired
    private DeviceElectricityDayMapper tbDeviceElectricityDayMapper;
    @Autowired
    private AlarmInfoMapper alarmInfoMapper;
    @Autowired
    private FTPUtils ftp;
    @Resource
    private DeviceGroupDeviceTypeMapper deviceGroupDeviceTypeMapper;
    @Resource
    private GroupDeviceService groupDeviceService;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return deviceMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(Device record) {
        return deviceMapper.insert(record);
    }

    @Override
    public int insertSelective(Device record) {
        return deviceMapper.insertSelective(record);
    }

    @Override
    public Device selectByPrimaryKey(Integer id) {
        return deviceMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Device record) {
        return deviceMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public Device selectProductionDeviceByClientId(String number) {
        return deviceMapper.selectProductionDeviceByClientId(number);
    }

    @Override
    public Device selectVwDeviceProduceById(Integer id) {
        return deviceMapper.selectVwDeviceProduceById(id);
    }

    @Override
    public int updateByPrimaryKey(Device record) {
        return deviceMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<Device> selectAllByParam(String param, Integer type, Integer enterpriseID, String[] areaArr, Integer[] deviceList,Integer bind) {
        return deviceMapper.selectAllByType(type, param, enterpriseID, areaArr, deviceList,bind);
    }

    @Override
    public List<CommonCount> getTotal(Integer type, Integer id, String[] areas, Integer[] group) {
        CommonCount commonCount = deviceMapper.getCount(type, id, areas, group);
        List<CommonCount> list = deviceMapper.selectCountGroupByStatusTwo(type, id, areas, group);
        list.add(commonCount);
        return list;
    }

    @Override
    public HashMap<String, List<Device>> getDeviceByStatus(Integer id, String[] areaArr, Integer[] deviceList) {
        HashMap<String, List<Device>> map = new HashMap<>(4);
        List<Device> devices = deviceMapper.selectAllByType(1, null, id, areaArr, deviceList, null);
        List<Device> deviceList1 = new ArrayList<>();
        List<Device> deviceList2 = new ArrayList<>();
        List<Device> deviceList3 = new ArrayList<>();
        List<Device> deviceList4 = new ArrayList<>();
        for (Device device : devices) {
            switch (device.getStatus()) {
                case 1:
                    deviceList1.add(device);
                    break;
                case 2:
                    deviceList2.add(device);
                    break;
                case 3:
                    deviceList3.add(device);
                    break;
                case 4:
                    deviceList4.add(device);
                    break;
            }
        }
        map.put("jobs", deviceList1);
        map.put("standby", deviceList2);
        map.put("down", deviceList3);
        map.put("malfunction", deviceList4);
        return map;
    }

    @Override
    public Device selectDeviceByNumber(String number, int type) {
        return deviceMapper.selectOneBySn(number, type);
    }

    @Override
    public Device selectDeviceById(Integer id, Integer type) {
        return deviceMapper.selectonebyidAndType(id, type);
    }

    @Override
    @Transactional
    public void addProductionEquipment(Device device) throws IOException {
        uploadDevicePhoto(device);
        device.setType(1);
        device.setStatus(2);
        device.setLastMaintenance(DateUtil.date());
        deviceMapper.insertSelective(device);
        /*如果设备类型不为空 去把设备和设备分组关联起来*/
        if (ObjectUtil.isNotNull(device.getDeviceType())) {
            /*根据企业ID和设备类型查出分组ID*/
            List<Integer> ids = deviceGroupDeviceTypeMapper.selectListByEnterpiseAndDeviceType(device.getEnterpise(), device.getDeviceType());
            List<GroupDevice> list = new ArrayList<>();
            for (Integer id : ids) {
                GroupDevice groupDevice = new GroupDevice();
                groupDevice.setDevice(device.getId());
                groupDevice.setGroup(id);
                list.add(groupDevice);
            }
            groupDeviceService.saveBatch(list);
        }

        /*  *//*添加完设备后去维保数据表添加一条数据*//*
        MaintenanceInfo maintenanceInfo = new MaintenanceInfo();
        maintenanceInfo.setSn(device.getSn());
        maintenanceInfo.setStatus(2);
        maintenanceInfo.setType(2);
        maintenanceInfo.setNextMaintenanceTime(DateUtil.offsetDay(DateUtil.date(), device.getMaintenanceCycle()));
        maintenanceInfoMapper.insertSelective(maintenanceInfo);*/
    }

    @Override
    public void deleteDeviceById(Integer id) throws DeviceException {
        List<Device> list = deviceMapper.selectAllByGroup(id);
        if (list.size() > 0) {
            throw new DeviceException("当前采集设备有生产设备");
        }
        deviceMapper.deleteById(id);
    }

    @Override
    public void updateByPrimaryKeySelective2(Device device) {

        deviceMapper.updateByPrimaryKeySelective(device);
    }

    @Override
    @Transactional
    public void updateByPrimaryKeySelectiveAndFileUpload(Device device) throws IOException {
        uploadDevicePhoto(device);
        updateByPrimaryKeySelective(device);
       /*修改维保信息
        MaintenanceInfo maintenanceInfo = maintenanceInfoMapper.selectOneBySnAndType(device.getSn(), 2);
        maintenanceInfo.setNextMaintenanceTime(DateUtil.offsetDay(DateUtil.date(), device.getMaintenanceCycle()));
        maintenanceInfo.setUpdateTime(DateUtil.date());
        maintenanceInfoMapper.updateByPrimaryKeySelective(maintenanceInfo);*/
    }

    @Override
    public Device getProduceDefaultDevice(String[] area, Integer[] deviceList) {
        return deviceMapper.getFirstDeviceByArea(area, deviceList);
    }

    @Override
    public List<Device> selectDeviceByCompany(Integer company, Integer id) {
        if (ObjectUtil.isNull(id) || id.equals(0)) {
            return deviceMapper.selectAllByTypeAndEnterpiseTwo(0, company, "");
        }
        return deviceMapper.selectAcquisitionEquipmentById(company, id);
    }

    @Override
    public List<Device> selectDeviceByCompanyTwo(Integer company) {
        return deviceMapper.selectAllByTypeAndEnterpiseTwo(0, company, "");
    }

    @Override
    public DeviceExtraData findElectricityAnalysisData(Integer id) {
        return deviceExtraDataMapper.selectByDeviceId(id);
    }

    @Override
    public List<DateAndString> findTodayElectricity(Integer id) {
        return deviceExtraDataMapper.selectTodayElectricity(id);
    }

    @Override
    public List<DateAndString> findRealPower(Integer id) {
        return deviceExtraDataMapper.selectRealPower(id);
    }

    @Override
    public List<DateAndString> findProductionTime(Integer id, String beginTime, String endTime, Integer type) {
        Date bDate;
        Date eDate;
        if (StringUtils.isBlank(beginTime)) {
            if (type == 1) {
                bDate = StringUtils.isBlank(beginTime) ? DateUtil.offsetDay(DateUtil.lastMonth(), -1) : DateUtil.parse(beginTime);
            } else {
                bDate = DateUtil.offsetDay(DateUtil.date(), -6);
            }
        } else {
            bDate = DateUtil.parseDate(beginTime);
        }
        if (StringUtils.isBlank(endTime)) {
            eDate = DateUtil.date();
        } else {
            eDate = DateUtil.parseDate(endTime);
        }
        return deviceExtraDataMapper.selectProductionTime(id, bDate, eDate);
    }


    @Override
    public List<DateAndString> findTodayElectricityByParam(Integer id, String beginTime, String endTime) {
        Date bDate;
        Date eDate;
        if (StringUtils.isBlank(beginTime) && StringUtils.isBlank(endTime)) {
            bDate = DateUtil.beginOfDay(toDay);
        } else if (StringUtils.isBlank(beginTime) && StringUtils.isNotBlank(endTime)) {
            bDate = DateUtil.offsetMonth(DateUtil.parseDate(endTime), -1);
        } else {
            bDate = DateUtil.parseDateTime(beginTime);
        }
        if (StringUtils.isBlank(endTime) && StringUtils.isBlank(beginTime)) {
            eDate = DateUtil.parseDateTime(DateUtil.now());
        } else if (StringUtils.isBlank(endTime) && StringUtils.isNotBlank(beginTime)) {
            eDate = DateUtil.offsetMonth(bDate, 1);
        } else {
            eDate = DateUtil.parseDateTime(endTime);
        }
        return deviceExtraDataMapper.selectTodayElectricityByParam(id, bDate, eDate);
    }

    @Override
    public List<DateAndString> findRealPowerParam(Integer id, String beginTime, String endTime, Integer type) {
        Date bDate;
        Date eDate;
        if (StringUtils.isBlank(beginTime) && StringUtils.isBlank(endTime)) {
            bDate = DateUtil.beginOfDay(toDay);
        } else if (StringUtils.isBlank(beginTime) && StringUtils.isNotBlank(endTime)) {
            bDate = DateUtil.offsetMonth(DateUtil.parseDate(endTime), -1);
        } else {
            bDate = DateUtil.parseDateTime(beginTime);
        }
        if (StringUtils.isBlank(endTime) && StringUtils.isBlank(beginTime)) {
            if (ObjectUtil.isNull(type)) {
                eDate = DateUtil.date();
            } else if (type == 2) {
                eDate = DateUtil.endOfDay(DateUtil.yesterday());
            } else {
                eDate = DateUtil.date();
            }
        } else if (StringUtils.isBlank(endTime) && StringUtils.isNotBlank(beginTime)) {
            eDate = DateUtil.offsetMonth(bDate, 1);
        } else {
            eDate = DateUtil.parseDateTime(endTime);
        }
        return deviceExtraDataMapper.selectRealPowerParam(id, bDate, eDate);
    }

    @Override
    public List<DeviceExtraData> findElectricityAnalysisDataByParam(Integer id, String beginTime, String endTime) {
        Date bDate;
        Date eDate;
        if (StringUtils.isBlank(beginTime) && StringUtils.isBlank(endTime)) {
            bDate = DateUtil.beginOfDay(toDay);
        } else if (StringUtils.isBlank(beginTime) && StringUtils.isNotBlank(endTime)) {
            bDate = DateUtil.offsetMonth(DateUtil.parseDate(endTime), -1);
        } else {
            bDate = DateUtil.parseDateTime(beginTime);
        }
        if (StringUtils.isBlank(endTime) && StringUtils.isBlank(beginTime)) {
            eDate = DateUtil.date();
        } else if (StringUtils.isBlank(endTime) && StringUtils.isNotBlank(beginTime)) {
            eDate = DateUtil.offsetMonth(bDate, 1);
        } else {
            eDate = DateUtil.parseDateTime(endTime);
        }
        return deviceExtraDataMapper.selectElectricityAnalysisDataByParam(id, bDate, eDate);
    }

    @Override
    public PowerConsumptionStatistics findPowerConsumptionStatistics(Integer id) {
        PowerConsumptionStatistics pcs = new PowerConsumptionStatistics();
        CommonKeyValue value1 = deviceMapper.selectToDayStatisticsByDeviceId(id);
        if (ObjectUtil.isNotNull(value1)) {
            pcs.setElectricityCharge(Double.parseDouble((String) value1.getValue()));
        }
        CommonKeyValue value2 = deviceMapper.selectYesterdayStatisticsDeviceId(id);
        if (ObjectUtil.isNotNull(value2)) {
            //昨日用电量
            Double YEP = Double.parseDouble((String) value2.getKey());
            Double YEB = Double.parseDouble((String) value2.getValue());
            pcs.setYEB(YEB);
            //昨日平均电价
            pcs.setDailyPrice(CalculateUtils.div(YEB, YEP, 4));
        }
        CommonKeyValue value3 = deviceMapper.selectthisMonthStatisticsByDeviceId(id);
        if (ObjectUtil.isNotNull(value3)) {
            pcs.setEBTM((Double) value3.getValue());
        }
        CommonKeyValue value4 = deviceMapper.selectlastMonthStatisticsByDeviceId(id);
        if (ObjectUtil.isNotNull(value4)) {
            pcs.setEPLM(CalculateUtils.div(Double.parseDouble(value4.getValue().toString()), Double.parseDouble(value4.getKey().toString()), 4));
        }
        DeviceOriginData deviceOriginData = deviceOriginDataMapper.selectByDeviceId(id);
        if (deviceOriginData != null) {
            String powerActive = deviceOriginData.getPowerActive();
            String powerReacitive = deviceOriginData.getPowerReacitive();
//            实时有功
            pcs.setRealActive(StringUtils.isNoneBlank(powerActive) ? Double.parseDouble(powerActive) : 0.00);
//            实时无功
            pcs.setRealReactive(StringUtils.isNoneBlank(powerReacitive) ? Double.parseDouble(powerReacitive) : 0.00);
        }
        return pcs;
    }

    @Override
    public DeviceData findGISDeviceInfo(Integer id) {
        DeviceElectricityDay electricityDay = tbDeviceElectricityDayMapper.selectDyDeviceIdToDay(id);
        Device device = deviceMapper.selectByPrimaryKey(id);
        DeviceData deviceData = new DeviceData();
        deviceData.setName(device.getName());
        if (StringUtils.isNotBlank(device.getPosition())) {
            String[] split = device.getPosition().split(",");
            double x = Double.parseDouble(split[0]);
            double y = Double.parseDouble(split[1]);
            deviceData.setX(x);
            deviceData.setY(y);
        }
        deviceData.setSn(device.getSn());
        deviceData.setStatus(device.getStatus());
        Company company = companyMapper.selectByPrimaryKey(device.getEnterpise());
        deviceData.setProvince(company.getProvince());
        deviceData.setCity(company.getCity());
        deviceData.setCompany(company.getName());
        if (ObjectUtil.isNull(electricityDay)) {
            deviceData.setTodayEC(0.0);
            deviceData.setTodayEF(0.0);
        } else {
            deviceData.setTodayEC(Double.parseDouble(electricityDay.getPower()));
            deviceData.setTodayEF(Double.parseDouble(electricityDay.getBill()));

        }
        String time = deviceExtraDataMapper.selectTodayProductionTime(id);
        deviceData.setProductionTime(time);
        return deviceData;
    }

    @Override
    public List<Device> findDeviceLikeParam(String param, String[] areaArr, Integer[] deviceList) {
        return deviceMapper.selectAllByTypeAndLikeParam(1, param, areaArr, deviceList);
    }

    @Override
    public List<Device> findDeviceByEId(Integer id, Integer[] deviceList) {

        return deviceMapper.selectAllByTypeAndEnterpise(1, id, "", deviceList);
    }

    @Override
    public List<DeviceNode> getDeviceByEnterpriseId(String[] enterpriseIds, String param, Integer[] deviceList) {
        return deviceMapper.getDeviceByTypeAndEnterprise(enterpriseIds, param, deviceList);
    }


    @Override
    public Message getDeviceListData(Integer enterpriseID, String param, Integer num, String sortParam, Integer pageIndex, Integer pageSize, Integer deviceType, Integer[] deviceList) {
        PageHelper.startPage(pageIndex, pageSize);
        List<DeviceRealData> list = deviceMapper.selectAllDeviceBasicData(enterpriseID, param, num, sortParam, deviceType, deviceList);
        PageInfo<DeviceRealData> info = new PageInfo(list);
     /*   for (DeviceRealData deviceRealData : info.getList()) {
            deviceRealData.setDeviceExtraData(deviceExtraDataMapper.selectByDeviceId(deviceRealData.getId()));
            String productionTime = deviceExtraDataMapper.selectTodayProductionTime(deviceRealData.getId());
            deviceRealData.setProductionTime(productionTime == null ? "0" : productionTime);
        }*/
        return Message.success()
                .addData("data", info.getList())
                .addData("total", info.getTotal())
                .addData("pages", info.getPages());
    }

    @Override
    public List<DeviceRealData> apiGetDeviceListDataTo(Integer enterprise, String param, Integer[] deviceList) {
        List<DeviceRealData> list = deviceMapper.selectAllDeviceBasicData(enterprise, param, null, null, 0, deviceList);
        for (DeviceRealData deviceRealData : list) {
            deviceRealData.setDeviceExtraData(deviceExtraDataMapper.selectByDeviceId(deviceRealData.getId()));
            String productionTime = deviceExtraDataMapper.selectTodayProductionTime(deviceRealData.getId());
            deviceRealData.setProductionTime(productionTime == null ? "0" : productionTime);
        }
        return list;
    }

    @Override
    public List<MaintenanceView> getMaintenanceList(String[] ids, Integer expire, Integer[] deviceList) {
        return deviceMapper.getDeviceMaintenance(ids, expire, deviceList);
    }

    @Override
    public List<Map<String, Object>> findUsageRate(Integer enterprise, Integer[] deviceList) {
        Date beginDate = DateUtil.yesterday();
        Date endDate = DateUtil.offsetDay(beginDate, -6);
        return deviceMapper.selectUsageRate(enterprise, beginDate, endDate, deviceList);
    }

    @Override
    public List<KeyValueTwo> findUsageRateTwo(Integer enterprise, String datetime, String deviceName, Integer deviceType, Integer[] deviceList) {
        Date beginDate = DateUtil.yesterday();
        Date endDate = DateUtil.yesterday();
        if (StringUtils.isNotBlank(datetime)) {
            String[] split = datetime.split(" ~ ");
            beginDate = DateUtil.parseDate(split[0]);
            endDate = DateUtil.parseDate(split[1]);
        }
        return deviceMapper.selectUsageRateTwo(enterprise, beginDate, endDate, deviceName, deviceType, deviceList);
    }


    @Override
    public List<DateAndString> findEnterprisePower(Integer enterprise) {

        return deviceMapper.selectEnterprisePower(enterprise);
    }

    @Override
    public List<DeviceExtraData> findEnterpriseExtraData(Integer enterprise, Integer[] deviceList) {
        return deviceMapper.selectEnterpriseExtraData(enterprise, deviceList);
    }

    @Override
    public String findEnterpriseHealth(Integer enterprise) {
        return deviceMapper.selectEnterpriseHealth(enterprise);
    }

    @Override
    public List<DeviceOriginData> findEnterpriseDeviceOriginData(Integer enterprise, Integer[] deviceList) {
        return deviceOriginDataMapper.selectByEnterprise(enterprise, deviceList);
    }

    @Override
    public String findToDayProductionTime(Integer enterprise, Integer[] deviceList) {
        if (ObjectUtil.isNotEmpty(deviceList)) {
            return deviceMapper.selectToDayProductionTimeOne(enterprise, deviceList);
        } else {
            return deviceMapper.selectToDayProductionTime(enterprise, deviceList);
        }

    }

    @Override
    public EnterpriseProductionTime findMoreProductionTime(Integer enterprise, Integer[] deviceList) {
        Date lastWeekEnd = DateUtil.lastWeek();
        Calendar cld = Calendar.getInstance();
        int firstDay = cld.get(Calendar.DAY_OF_WEEK) - 2;
        Date lastWeekBegin = DateUtil.offsetDay(lastWeekEnd, -firstDay);
        if (ObjectUtil.isNotEmpty(deviceList)) {
            return deviceMapper.getMoreProductionTimeOne(deviceList, lastWeekBegin, lastWeekEnd);
        } else {
            return deviceMapper.getMoreProductionTime(enterprise, lastWeekBegin, lastWeekEnd);
        }

    }

    @Override
    public List<KeyValue> findEnterprisePowerData(Integer enterprise) {
        return deviceMapper.selectEnterprisePowerData(enterprise);
    }

    @Override
    public CommonTimePojo findElectricityStatistics(Integer enterprise, Integer[] deviceList) {
        CommonTimePojo timePojo = new CommonTimePojo();
        CommonKeyValue value1 = deviceMapper.selectToDayStatistics(enterprise, deviceList);
        if (ObjectUtil.isNotNull(value1)) {
            timePojo.setToDay(value1.getKey());
            timePojo.setToDayData(value1.getValue());
        }
        CommonKeyValue value2 = deviceMapper.selectYesterdayStatistics(enterprise, deviceList);
        if (ObjectUtil.isNotNull(value2)) {
            timePojo.setYesterday(value2.getKey());
            timePojo.setYesterdayData(value2.getValue());
        }
        CommonKeyValue value3 = deviceMapper.selectthisMonthStatistics(enterprise, deviceList);
        if (ObjectUtil.isNotNull(value3)) {
            timePojo.setThisMonth(value3.getKey());
            timePojo.setThisMonthData(value3.getValue());
        }
        CommonKeyValue value4 = deviceMapper.selectlastMonthStatistics(enterprise, deviceList);
        if (ObjectUtil.isNotNull(value4)) {
            timePojo.setLastMonth(value4.getKey());
            timePojo.setLastMonthData(value4.getValue());
        }
        return timePojo;
    }

    @Override
    public List<DeviceExtraData> findElectricityParameters(Integer enterprise, String month, Integer[] deviceList) {
        return deviceExtraDataMapper.selectElectricityParameters(enterprise, month, deviceList);
    }

    @Override
    public Device selectdeviceByGroup(Integer group) {
        return deviceMapper.selectOneByGroupAndType(group, 1);
    }

    @Override
    public Device selectByClientId(String clientID) {
        return deviceMapper.selectonebyclientIdAndType(clientID, 0);
    }

    @Override
    public String findTodayProductionTime(Integer deviceId) {
        return deviceExtraDataMapper.selectTodayProductionTime(deviceId);
    }


    @Override
    public List<KeyValue> findDeviceStatusByParam(Integer enterprise, String param, Integer deviceType, Integer[] deviceList) {
        return deviceMapper.selectDeviceStatusByParam(enterprise, param, deviceType, deviceList);
    }

    @Override
    public Map<String, Object> findReportConclusion(Integer enterprise, String month, Integer[] deviceList) {
        Date date = DateUtil.date();
        int offset = -1;
        if (StringUtil.isNotEmpty(month)) {
            month += "-01 00:00:00";
            date = DateUtil.parseDate(month);
            offset = 0;
        }
        Date offsetMonth = DateUtil.offsetMonth(date, offset);
        Map<String, Object> map = new HashMap();
        map.put("avgUtilization", deviceMapper.selectLastMonthAvgDeviceUsageRateByEnterpris(enterprise, offsetMonth, deviceList));
        CommonKeyValue keyValue = deviceMapper.selectlastMonthMaxDeviceUsageRateByEnterpris(enterprise, offsetMonth, deviceList);
        if (ObjectUtil.isNotNull(keyValue)) {
            map.put("maxUtilization", keyValue.getKey());
            map.put("deviceName", keyValue.getValue());
        }
        map.put("Overload", alarmInfoMapper.findCountAlarm(enterprise, offsetMonth, "超限", deviceList));
        map.put("unbalance", alarmInfoMapper.findCountAlarm(enterprise, offsetMonth, "三相不平衡", deviceList));
        map.put("healthIndex", alarmInfoMapper.findCountAlarm(enterprise, offsetMonth, "健康指数过低", deviceList));
        CommonKeyValue Overload = alarmInfoMapper.selectlastMonthDeviceData(enterprise, offsetMonth, "超限", deviceList);
        CommonKeyValue unbalance = alarmInfoMapper.selectlastMonthDeviceData(enterprise, offsetMonth, "三相不平衡", deviceList);
        CommonKeyValue healthIndex = alarmInfoMapper.selectlastMonthDeviceData(enterprise, offsetMonth, "健康指数过低", deviceList);
        if (ObjectUtil.isNotNull(Overload)) {
            map.put("totalOverload", Overload.getKey());
            map.put("overloadDeviceName", Overload.getValue());
        }
        if (ObjectUtil.isNotNull(unbalance)) {
            map.put("totalUnbalance", unbalance.getKey());
            map.put("unbalanceDeviceName", unbalance.getValue());
        }
        if (ObjectUtil.isNotNull(healthIndex)) {
            map.put("totalHealthIndex", healthIndex.getKey());
            map.put("healthIndexDevice", healthIndex.getValue());
        }
        return map;
    }

    @Override
    public List<Device> selectCollectionEquipment(String param, String[] areaArr, Integer[] deviceList, Integer bind,Integer status,Integer company) {
        return deviceMapper.selectCollectionEquipment(param, areaArr, deviceList, bind,status,company);
    }

    @Override
    public List<KeyValue> findProductionTimeHistogram(Integer enterprise, String time, Integer[] deviceList) {
        String bDate = DateUtil.formatDate(DateUtil.offsetDay(new Date(), -6));
        String eDate = DateUtil.today();
        if (StringUtils.isNotBlank(time)) {
            String[] split = time.split(" ~ ");
            bDate = split[0];
            eDate = split[1];
        }

        if (ObjectUtil.isNotEmpty(deviceList)) {
            return deviceMapper.selectProductionTimeByWeekAndEnterpriseOne(bDate, eDate, deviceList);
        } else {
            return deviceMapper.selectProductionTimeByWeekAndEnterprise(bDate, eDate, enterprise);
        }

    }

    @Override
    public List<Device> selectDeviceByDeviceType(Integer deviceType, String[] areaArr, Integer[] deviceList) {
        return deviceMapper.selectAllByDeviceType(deviceType, 1, areaArr, deviceList);
    }

    @Override
    public List<KeyValue> getTheEnergyYouUseToday(Integer enterprise, Integer[] deviceList) {
        return deviceMapper.selectTheEnergyYouUseToday(enterprise, deviceList);
    }

    @Override
    public boolean unbindDevice(Integer id) {

        return deviceMapper.updateDeviceGroupById(id) > 0;
    }

    @Override
    public Device findDeviceBySnAndType(String sn, Integer type) {
        return deviceMapper.selectOneBySn(sn, type);
    }

    @Override
    public List<CommonKeyValue> getAvgProductionTime(String dateTime, Integer enterprise, Integer[] deviceList) {
        String beginDate = DateUtil.formatDate(DateUtil.offsetDay(new Date(), -29));
        String endDate = DateUtil.today();
        if (StringUtils.isNotBlank(dateTime)) {
            String[] split = dateTime.split(" ~ ");
            beginDate = split[0];
            endDate = split[1];
        }
        return deviceMapper.selectAvgProductionTime(beginDate, endDate, enterprise, deviceList);
    }

    @Override
    public List<ProductionDetails> getProductionDetails(String dateTime, Integer enterprise, Integer[] deviceList) {
        String beginDate = DateUtil.formatDate(DateUtil.offsetDay(new Date(), -29));
        String endDate = DateUtil.today();
        if (StringUtils.isNotBlank(dateTime)) {
            String[] split = dateTime.split(" ~ ");
            beginDate = split[0];
            endDate = split[1];
        }
        return deviceMapper.selectProductionDetails(beginDate, endDate, enterprise, deviceList);
    }

    @Override
    public List<Map<String, Object>> countDeviceType(Integer enterprise, Integer[] deviceList) {
        return deviceMapper.countDeviceType(enterprise, deviceList);
    }

    @Override
    public List<Map<String, Object>> getMorePowerConsumption(String startTime, String endTime, Integer enterprise, Integer[] deviceList) {
        return deviceMapper.selectEnergyUsedGroupByDayAndEnterprise(startTime, endTime, enterprise, deviceList);
    }

    @Override
    public List<Map<String, Object>> getMorePowerConsumptionYear(String year, Integer enterprise, Integer[] deviceList) {
        if (StringUtils.isBlank(year)) {
            year = DateUtil.format(new Date(), "yyyy");
        }
        return deviceMapper.selectMorePowerConsumptionYear(year, enterprise, deviceList);
    }

    @Override
    public DeviceElectricityDay getMorePowerConsumptionDay(String day, Integer enterprise, Integer[] deviceList) {
        return deviceMapper.selectMorePowerConsumptionDay(day, enterprise, deviceList);
    }

    @Override
    public List<Map<String, Object>> getEnergyUsedByDay(String day, Integer enterprise, Integer[] deviceList) {
        return deviceMapper.selectEnergyUsedByDay(day, enterprise, deviceList);
    }

    @Override
    public List<MaintenanceView> getExtensionMaintenanceInfo(String[] ids, Integer expire, Integer[] deviceList) {
        return deviceMapper.selectExtensionMaintenanceInfo(ids, expire, deviceList);
    }

    @Override
    public List<DateAndString> findToDayPower(Integer enterprise, Integer[] deviceList) {
        return deviceMapper.selectToDayPower(enterprise, deviceList);
    }

    private void uploadDevicePhoto(Device device) throws IOException {
        if (device.getPhotoFile() != null && !"".equals(device.getPhotoFile().getOriginalFilename())) {
            MultipartFile file = device.getPhotoFile();
            String filename = IdUtil.fastSimpleUUID() + "." + FileUtils.getExt(file.getOriginalFilename());
            device.setImage(deviceDir + "/" + filename);
            ftp.upload(file.getInputStream(), filename, deviceDir);
            if (device.getThumbnail() != null && !"".equals(device.getThumbnail().getOriginalFilename())) {
                ftp.upload(device.getThumbnail().getInputStream(), "min" + filename, deviceDir);
            } else {
                ftp.upload(file.getInputStream(), "min" + filename, deviceDir);
            }
        }
    }
}




